//
//  Bundle+Ex.swift
//  
//
//  Created by tank on 2021/12/4.
//

import Foundation
import UIKit

public extension Extension where Base == Bundle {
    var appIcon: UIImage? {
        if let icons = base.infoDictionary?["CFBundleIcons"] as? [String: Any],
           let primaryIcon = icons["CFBundlePrimaryIcon"] as? [String: Any],
           let iconFiles = primaryIcon["CFBundleIconFiles"] as? [String],
           let lastIcon = iconFiles.last {
            return UIImage(named: lastIcon)
        }
        return nil
    }
    
    var appVersion: String {
        guard let infoDictionary = Bundle.main.infoDictionary else {
            return ""
        }

        let majorVersion: String = infoDictionary ["CFBundleShortVersionString"] as? String ?? "" // 主程序版本号
        let buildNumber: String = infoDictionary ["CFBundleVersion"] as? String ?? "" // 主程序build号

        return "v\(majorVersion).\(buildNumber)"
    }
    
    func data(forResource: String?, withExtension: String?) -> Data? {
        
        guard let resourceUrl = base.url(forResource: forResource,
                                         withExtension: withExtension) else {
            return nil
        }
        
        return try? Data(contentsOf: resourceUrl)
    }
    
    func string(forResource: String?, withExtension: String?) -> String? {
        guard let resourceUrl = base.url(forResource: forResource,
                                         withExtension: withExtension) else {
            return nil
        }
        
        return try? String(contentsOf: resourceUrl)
    }
}
